﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Mayfair.Core.Common.FormManager
{
    /// <summary>
    /// フォーム管理用コンテナ
    /// Container that manage form
    /// </summary>
    public class FormContainer
    {
        /// <summary>
        /// フォーム保持が目的のDictionary
        /// Dictionary whose purpose is keeping up forms
        /// </summary>
        private static Dictionary<Type, Form> dic = new Dictionary<Type, Form>();

        /// <summary>
        /// 1.　　フォームをDictionaryから取得
        /// 1-1.　フォームが存在しなければインスタンスを作成
        /// 1-2.　既にDisposeされていたら作り直し
        /// 1-3.　作ったらDictionaryに追加
        /// 1.　　Take the Form instance from dictionary
        /// 1-1.  If nothing, Create Form instance
        /// 1-2.  If it have already disposed, create it again
        /// 1-3.  Add it to the dictionary
        /// </summary>
        /// <param name="formType"></param>
        /// <returns></returns>
        public static Form GetForm(Type formType)
        {
            Form form;
            bool result = dic.TryGetValue(formType, out form);
            if (result)
            {
                if (form == null || form.IsDisposed)
                {
                    form = (Form)Activator.CreateInstance(formType);
                    dic.Remove(formType);
                    dic.Add(formType, form);
                }
            }
            else
            {
                form = (Form)Activator.CreateInstance(formType);
                dic.Add(formType, form);
            }
            return form;
        }
        
        /// <summary>
        /// 全てのフォームを閉じる
        /// Close the all forms
        /// </summary>
        public static void AllFormClose()
        {
            foreach (Form form in dic.Values)
            {
                if (form != null && !form.IsDisposed)
                {
                    form.Close();
                    form.Dispose();
                }
            }
            dic.Clear();
        }
        
        /// <summary>
        /// 自フォーム以外の全てのフォームを閉じる
        /// Close the non-active forms
        /// </summary>
        /// <param name="formType"></param>
        public static void AllFormClose(Type formType)
        {
            foreach (Form form in dic.Values)
            {
                if (form.GetType() != formType)
                {
                    if (form != null && !form.IsDisposed)
                    {
                        form.Close();
                        form.Dispose();
                    }
                }
            }
        }

    }
}
